<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "{{%user}}".
 *
 * @property integer $id
 * @property string $username
 * @property string $password_hash
 * @property string $mobile
 * @property integer $role
 * @property string $created
 * @property string $updated
 * @property integer $status
 * @property string $auth_key
 */
class User extends BaseUser
{
    const STATUS_DELETED = 0;
    const STATUS_ACTIVE = 10;
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%user}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['username', 'mobile'], 'required'],
            [['role', 'status'], 'integer'],
            [['created', 'updated'], 'safe'],
            [['username'], 'string', 'max' => 160],
            [['password_hash'], 'string', 'max' => 128],
            [['mobile'], 'string', 'max' => 11],
            [['auth_key'], 'string', 'max' => 64],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'username' => Yii::t('app', '用户名'),
            'password_hash' => Yii::t('app', '密码'),
            'mobile' => Yii::t('app', '手机'),
            'role' => Yii::t('app', '角色'),
            'created' => Yii::t('app', 'Created'),
            'updated' => Yii::t('app', 'Updated'),
            'status' => Yii::t('app', 'Status'),
            'auth_key' => Yii::t('app', 'Auth Key'),
        ];
    }

    /**
     * @inheritdoc
     * @return UserQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new UserQuery(get_called_class());
    }

    public static function findByUsername($username)
    {
        return static::findOne(['username' => $username]);
    }

    public function signup()
    {
        // 调用validate方法对表单数据进行验证，验证规则参考上面的rules方法
        if (!$this->validate()) {
            return null;
        }
        // 实现数据入库操作
        $user = new User();
        $user->username = $this->username;
        $user->mobile = $this->mobile;
        $user->status = 1;
        $user->role = 1;
        $user->created = date('Y-m-d');
        $user->updated = date('Y-m-d');
        // 设置密码，密码肯定要加密，暂时我们还没有实现，看下面我们有实现的代码
        $user->setPassword($this->password_hash);
        // 生成 "remember me" 认证key
        $user->generateAuthKey();
        // save(false)的意思是：不调用UserBackend的rules再做校验并实现数据入库操作
        // 这里这个false如果不加，save底层会调用UserBackend的rules方法再对数据进行一次校验，因为我们上面已经调用Signup的rules校验过了，这里就没必要在用UserBackend的rules校验了
//        print_r($user->attributes);die;
        if(!$user->save(false)){
            return print_r($user->getErrors());
        }else{
            return print_r($user->getErrors());
        }
        return $user->save(false);
    }

}
